package com.example.redis.mqtt;

import com.example.redis.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 消息订阅客户端
 * @author yanglingcong*/
@Component
@Slf4j
public class MqttSubClient {

    private MqttCallBackHandler mqttCallBackHandler;
    private MqttConfig mqttConfig;


    //todo 可能存在由于改变顺序之后导致的循环依赖问题！
//    public MqttSubClient(MqttCallBackHandler mqttCallBackHandler) throws MqttException {
//        this.mqttCallBackHandler = mqttCallBackHandler;
//        subscribe();
//
//    }
    // 解决了循环依赖问题
    @Autowired
    public MqttSubClient(MqttConfig mqttConfig) {
        this.mqttConfig = mqttConfig;
    }

    @Autowired
    public void setMqttCallBackHandler(MqttCallBackHandler mqttCallBackHandler) {
        this.mqttCallBackHandler = mqttCallBackHandler;
        subscribe();
    }

    public void subscribe()  {
        MqttClient client=null;

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        //断开之后自动重联
        connectOptions.setAutomaticReconnect(true);
        //设置会话心跳时间 代理和客户端在不发送消息的情况下可以忍受的最长时间
        connectOptions.setKeepAliveInterval(mqttConfig.getKeepAlive());
        //不建立持久会话
        connectOptions.setCleanSession(true);
        //用户名
        connectOptions.setUserName(mqttConfig.getUsername());
        //密码
        connectOptions.setPassword(String.valueOf(mqttConfig.getPassword()).toCharArray());

        String clientid = MqttClient.generateClientId();
        log.info("client ID:{}",clientid);


        try {
            client=new MqttClient(mqttConfig.getHost(), clientid, new MemoryPersistence());
            //MQTT连接
            client.connect(connectOptions);
            //消息回调
            client.setCallback(mqttCallBackHandler);

            client.subscribe(mqttConfig.getTopic(), mqttConfig.getQOS_1());

            log.info("MQTT消息订阅成功, host:{}, topic:{}",mqttConfig.getHost(),mqttConfig.getTopic());

            // client.subscribe("zmh/+/+",CommonConnectionConfig.QOS_1);

        }catch (MqttException e) {
            log.error("MQTT消息订阅异常",e);
            if(client!=null){
                log.error("MQTT消息订阅异常, uri:{}",client.getServerURI());
            }
            e.printStackTrace();
        }

    }
}
